<template>
  <div class="app-container">
   <el-row :gutter="10">
     <!-- 左边电子围栏 -->
     <el-col :span="10">
       <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80">

         <el-form-item label="围栏名称" prop="name">
           <el-input
             v-model="queryParams.name"
             placeholder="请输入围栏名称"
             clearable
             @keyup.enter.native="handleQuery"
           />
         </el-form-item>
         <el-form-item label="状态" prop="status">
           <el-select v-model="queryParams.status" placeholder="状态" clearable>
             <el-option
               v-for="dict in dict.type.sys_normal_disable"
               :key="dict.value"
               :label="dict.label"
               :value="dict.value"
             />
           </el-select>
         </el-form-item>
         <el-form-item>
           <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
           <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
         </el-form-item>
       </el-form>

       <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
           <el-button
             type="primary"
             plain
             icon="el-icon-plus"
             size="mini"
             @click="handleAdd"
             v-hasPermi="['device:fence:add']"
           >新增</el-button>
         </el-col>
         <el-col :span="1.5">
           <el-button
             type="success"
             plain
             icon="el-icon-edit"
             size="mini"
             :disabled="single"
             @click="handleUpdate"
             v-hasPermi="['device:fence:edit']"
           >修改</el-button>
         </el-col>
         <el-col :span="1.5">
           <el-button
             type="danger"
             plain
             icon="el-icon-delete"
             size="mini"
             :disabled="multiple"
             @click="handleDelete"
             v-hasPermi="['device:fence:remove']"
           >删除</el-button>
         </el-col>

         <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
       </el-row>

       <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="编号" align="center" prop="id" width="100"/>
         <el-table-column label="围栏名称" align="center" prop="name" />
         <el-table-column label="启用状态" align="center" prop="status">
           <template slot-scope="scope">
             <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
           </template>
          </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
           <template slot-scope="scope">
             <el-button
               size="mini"
               type="text"
               icon="el-icon-edit"
               @click="handleUpdate(scope.row)"
               v-hasPermi="['device:fence:edit']"
             >修改</el-button>
             <template>
              <el-button
               size="mini"
               type="text"
               icon="el-icon-edit"
               @click="handleUpdateStatus(scope.row)"
               v-hasPermi="['device:fence:edit']"
               v-if="scope.row.status==='0'"
             >禁用</el-button>
             <el-button
               size="mini"
               type="text"
               icon="el-icon-edit"
               @click="handleUpdateStatus(scope.row)"
               v-hasPermi="['device:fence:edit']"
               v-if="scope.row.status==='1'"
             >启用</el-button>
             </template>

             <el-button
               size="mini"
               type="text"
               icon="el-icon-delete"
               @click="handleDelete(scope.row)"
               v-hasPermi="['device:fence:remove']"
             >删除</el-button>
           </template>
         </el-table-column>
       </el-table>

       <pagination
         v-show="total>0"
         :total="total"
         :page.sync="queryParams.pageNum"
         :limit.sync="queryParams.pageSize"
         @pagination="getList"
       />



     </el-col>

      <!-- 右边百度地图 -->
     <el-col :span="14">
       <el-card class="box-card">
         <div slot="header" class="clearfix">
           <span>卡片名称</span>
           <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>
         </div>

         <div class="text item">
           <baidu-map class="bm-view-right" ak="3LgMlTyAIzk2ok2Sn5ZY6NPPmVQjMFch" center="重庆" :zoom="zoomRight" @ready="handlerRight">
              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
              <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
              <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>

              <template v-for="(item,index) in multipleData">
                <bm-circle  :center="calcPoint(item)" @click="infoWindowOpen(item)" :radius="item.radius" stroke-color="blue" :stroke-opacity="0.5" :stroke-weight="2"   :editing="false">
                </bm-circle>

                 <bm-label :content="showInfo(item)" :position="calcPoint(item)" :labelStyle="{color: 'red', fontSize : '14px'}" />
                <!-- <bm-info-window :position="calcPoint(item)" :show="item.mapShow" @close="infoWindowClose(item)" @open="infoWindowOpen(item)">
                       <p>负责人:{{item.userName}}</p>
                        <p>联系电话:{{item.mobile}}</p>
                 </bm-info-window> -->
              </template>
            </baidu-map>
         </div>
       </el-card>

     </el-col>
   </el-row>


   <!-- 添加或修改对话框 -->
   <el-dialog v-dialogDrag :title="title" :visible.sync="open" width="1000px"  append-to-body :close-on-click-modal="false" :before-close="cancel" >
     <el-row>
       <el-form ref="form" :model="form"   label-width="120px">
        <el-col :span="8">
          <el-form-item label="围栏名称" prop="name" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
            <el-input v-model="form.name" placeholder="请输入围栏名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="负责人" prop="userId" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
            <el-select v-model="form.userId"  placeholder="请选择" @change="userChange" >
               <el-option
                 v-for="item in userList"
                 :key="item.userId"
                 :label="item.userId+'-'+item.nickName"
                 :value="item.userId">
               </el-option>
             </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话" prop="mobile" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
            <el-input v-model="form.mobile" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="电子围栏半径" prop="radius" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
            <el-input v-model="form.radius" placeholder="请输入电子围栏半径" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="中心点经度" prop="longitude" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
            <el-input v-model="form.longitude" placeholder="请输入经度" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="中心点纬度" prop="latitude" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
            <el-input v-model="form.latitude" placeholder="请输入纬度" />
          </el-form-item>
        </el-col>

        <!-- <el-col :span="8">
          <el-form-item label="激活状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->

        <el-col :span="16">
          <el-form-item label="中心点位置" prop="address" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
            <el-input v-model="form.address" placeholder="请输入中心点位置" />
          </el-form-item>
        </el-col>


      <el-col :span="24">
           <baidu-map class="bm-view" ak="3LgMlTyAIzk2ok2Sn5ZY6NPPmVQjMFch" center="重庆" :zoom="zoom" @ready="handler">
               <bm-control>
                   <el-select v-model="mapAddressuid"  placeholder="请选择" @change="changeAddress">
                      <el-option
                        v-for="item in surroundingPois"
                        :key="item.uid"
                        :label="item.address"
                        :value="item.uid">
                      </el-option>
                    </el-select>
               </bm-control>
              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
               <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>
               <bm-circle v-if="showCircle" :center="circleCenter" :radius="circleRadius" stroke-color="blue" :stroke-opacity="0.5" :stroke-weight="2" @lineupdate="updateCirclePath" :editing="true"></bm-circle>

           </baidu-map>

      </el-col>

       </el-form>

      </el-row>
     <div slot="footer" class="dialog-footer">
       <el-button type="primary" @click="submitForm">确 定</el-button>
       <el-button @click="cancel">取 消</el-button>
     </div>
   </el-dialog>




  </div>
</template>


<script>
import { listApi, findByIdApi, addApi, updateApi, deleteApi ,disableApi} from "@/api/hat/fence.js";
import {allUser} from '@/api/system/user.js'
import { BaiduMap, BmMarker,BmScale,BmLabel,BmInfoWindow, BmNavigation,BmGeolocation,BmCityList,BmControl,BmAutoComplete,BmMapType,BmCircle} from 'vue-baidu-map'
 //https://blog.csdn.net/weixin_50885665/article/details/131222494
//https://dafrok.github.io/vue-baidu-map/#/zh/overlay/circle
export default {
  name: "Fence",
  dicts: ['sys_normal_disable'],
  components: {
     BaiduMap,
     BmScale,
     BmNavigation,
     BmGeolocation,
     BmCityList,
     BmMarker,
     BmControl,
     BmAutoComplete,
     BmMapType,
     BmCircle,
     BmLabel,
     BmInfoWindow
   },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中的数据
      multipleData:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      copyform:{},
      zoom: 13,
      BMap: undefined,
      map: undefined,
      zoomRight: 13,
      BMapRight: undefined,
      mapRight: undefined,
      //建议位置
      surroundingPois:[],
      openAddress: false,
      mapAddressuid: undefined,

      //负责ren列表
      userList: [],

      //已经绑定了电子围栏的负责人
      fenceUserList: ["1"],
    };
  },
  created() {
    this.getList();
    //this.fetchAllUser()
  },
  methods: {

    userChange(userId){
       const arr=this.userList.filter(p=>p.userId===userId);
       if(arr.length>0){
         this.form.mobile=arr[0].phonenumber
       }
    },
   async fetchAllUser(userId){
      allUser(userId).then(resp=> {
        console.log(resp)
        this.userList= resp.data
      })
    },
    handler ({BMap, map}) {

      const thatVue=this;

       this.BMap=BMap
       this.map=map
       //允许鼠标绽放地图
       this.map.enableScrollWheelZoom(true);
       this.zoom = 13
       //绑定一个点事事件
       this.map.addEventListener('click', function (e) {
          // alert('点击位置经纬度：' + e.latlng.lng + ',' + e.latlng.lat);
          console.log(e)

          //重新清空表单的数据
          thatVue.reset()


          //根据坐标解析位置
          let geoc = new BMap.Geocoder();
           geoc.getLocation(e.point, function(rs){
             console.log(rs);
              thatVue.surroundingPois=[]
              //推荐
              thatVue.surroundingPois=rs.surroundingPois;
              if(thatVue.surroundingPois && thatVue.surroundingPois.length==0 ){
                   let info={}
                   info.address= rs.address
                info.point = rs.point
                //当鼠标点到的地方 没有推荐位置的时候 uid就会为undefined 这时候需要手动填入一个uid
                if (rs.uid == undefined) {
                    info.uid=1
                } else {
                  info.uid= rs.uid
                   }
                   thatVue.surroundingPois.push(info)
              }
           })

       });

    },
    handlerRight({BMap, map}){
      this.BMapRight=BMap
      this.mapRight=map
      //允许鼠标绽放地图
      this.mapRight.enableScrollWheelZoom(true);
      this.zoomRight = 13
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listApi(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: this.form.name,
        userId: this.form.userId,
        mobile: this.form.mobile,
        id:this.form.id,
        status: "0",
        radius: 0
      };
      this.mapAddressuid= undefined
      this.surroundingPois=[]
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      //清空原先画好的图形
       this.multipleData=[]

      //清空地图上面的图层
      this.$nextTick(() => {
         this.multipleData=selection
      });
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
   async handleAdd () {
      this.form.name = undefined
      this.form.userId = undefined
      this.form.mobile = undefined

      await this.fetchAllUser()

      if(this.userList.length===0){
         this.$modal.msgSuccess("没有可用的用户，不能添加电子围栏");
         return;
      }

      this.reset();
      this.open = true;
      this.title = "添加电子围栏";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.fetchAllUser(row.userId)
      const id = row.id || this.ids
      findByIdApi(id).then(response => {
        console.log(response)
        this.form = response;
        this.open = true;
        this.title = "修改电子围栏";
      });
    },
    handleUpdateStatus (row) {
      this.fetchAllUser(row.userId)
      if (row.status === "0") {
        disableApi(row.id).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.getList();
      })
      } else {
        findByIdApi(row.id).then(response => {
        console.log(response)
        this.form = response;
        this.form.status="0"
        this.open = true;
        this.title = "启用电子围栏";
      });
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateApi(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(e=>{
               this.open=false;
            });
          } else {
            addApi(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(e=>{
               this.open=false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + id + '"的数据项？').then(function () {
        console.log(id)
        return deleteApi(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    updateCirclePath (e) {
      console.log(e)
      console.log( e.target.getCenter())
      console.log( e.target.getRadius())
      setTimeout(()=> {
         this.form.radius=e.target.getRadius()
      },500)


      //this.form.radius = e.target.getRadius()
        // this.circlePath.center = e.target.getCenter()
        // this.circlePath.radius = e.target.getRadius()
    },
    changeAddress(uid){
      const arr=this.surroundingPois.filter(p=>p.uid===uid);
      if(arr && arr.length>0){
        const point = arr[0].point
        this.$set(this.form,"latitude", point.lat)
        this.$set(this.form,"longitude", point.lng)
        this.$set(this.form,"address",arr[0].address)
        if(!this.form.radius){
           this.$set(this.form,"radius",3000)
        }
      }
    },
    //构造坐标，还原数据
    calcPoint(item){
      return  {
       lng: item.longitude,
       lat: item.latitude
       }
    },
    //显示信息
    infoWindowOpen(item){
      item.mapShow=true
    },
    infoWindowClose(item){
      item.mapShow=false
    },
    showInfo(item){
      return `<p>负责人:${item.userName}</p>
             <p>联系电话:${item.mobile}</p>`

    }
  },
  computed:{
     //要不要显示圆
     showCircle(){
        if( this.form.longitude && this.form.latitude && this.form.radius){
          return true
        }else{
          return false
        }
     },
     //半径
     circleRadius(){
        if(this.form.radius){
          return this.form.radius
        }else{
          return 0;
        }
     },
      circleCenter() {
         return  {
          lng: this.form.longitude,
          lat: this.form.latitude
          }
      }
  }
};
</script>

<style scoped>

  .bm-view {
    width: 100%;
    height:500px;
  }

  .bm-view-right{
    width: 100%;
    height:800px;
  }


</style>
